//
//  LJUserpic.m
//  LJClientKit
//
//  Created by che on 13/7/09.
//  Copyright 2009 AntonChebotaev. All rights reserved.
//

#import "LJUserpic.h"

// Exceptions
NSString * const LJUserpicBadInitException = @"LJUserpicBadInitException";

// Notifications
NSString * const LJUserpicWillLoadImageNotification = @"LJUserpicWillLoadImageNotification";
NSString * const LJUserpicDidLoadImageNotification = @"LJUserpicDidLoadImageNotification";

@implementation LJUserpic

@synthesize keyword;
@synthesize image;
@synthesize url;

- (id)init {
	[self dealloc];
    @throw [NSException exceptionWithName:LJUserpicBadInitException
								   reason:@"Initialize LJUserpic with simple init without keyword and url"
								 userInfo:nil];
    return nil;	
}

- (void)dealloc {
	if (image) {
		[image release];
	}
	[keyword release];
	[url release]; 
	[super dealloc];
}

- initWithKeyword:(NSString *)aKeyword andURL:(NSURL *)anURL {
	self = [super init];
	if (self) {
		keyword = [aKeyword retain];
		NSAssert(keyword != nil, @"LJUserpic initializated with blank keyword.");
		url = [anURL retain];
    }
    return self;	
}

+ userpicWithKeyword:(NSString *)aKeyword andURL:(NSURL *)anURL {
	LJUserpic * userpic = [[LJUserpic alloc] initWithKeyword:aKeyword andURL:anURL];
	return [userpic autorelease];
}

- (id)initWithCoder:(NSCoder *)decoder {
	self = [super init];
    if (self) {
        keyword = [[decoder decodeObjectForKey:@"LJUserpicCodingKeyword"] retain];
		url = [[decoder decodeObjectForKey:@"LJUserpicCodingURL"] retain];
		image = [[decoder decodeObjectForKey:@"LJUserpicCodingImage"] retain];
		
        NSAssert(keyword != nil, @"LJUserpic decoded without a keyword.");
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:keyword forKey:@"LJUserpicCodingKeyword"];
    [encoder encodeObject:url 	  forKey:@"LJUserpicCodingURL"];
	[encoder encodeObject:image   forKey:@"LJUserpicCodingImage"];
}

- (NSString *)description {
	return [NSString stringWithFormat:@"%@@%@", keyword, [url absoluteURL]];
}

- (BOOL)isEqual:(id)object {
	return [object isMemberOfClass:[LJUserpic class]] && [[self description] isEqual:[object description]];
}

- (NSUInteger)hash {
	return [[self description] hash];
}

- (void)reloadImage {
	[[NSNotificationCenter defaultCenter] postNotificationName:LJUserpicWillLoadImageNotification object:self];
	[self willChangeValueForKey:@"image"];
	
	@synchronized(self) {
		if (image) {
			[image release];
		}
		image = [[NSImage alloc] initWithContentsOfURL:url];		
	}	
	
	[self didChangeValueForKey:@"image"];
	[[NSNotificationCenter defaultCenter] postNotificationName:LJUserpicDidLoadImageNotification object:self];
}

@end
